package network;

import game.GameManager;
import gui.GamePlayPanel;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class ReceiverProcessor extends Thread {
	private Socket socket;
	private boolean host;
	private String tableName;
	private GameManager manager;
	private PlayerJoined delegate;
	public ReceiverProcessor(Socket socket) {
		this.socket = socket;
		//notifier = n;
		
	}
	public ReceiverProcessor(Socket s, GameManager manager, PlayerJoined joiner) {
		this(s);
		this.manager = manager;
		delegate = joiner;
	}
	public void makeHost(boolean host, String tableName){
		this.host = host;
		this.tableName = tableName;
	}
	public void run() {
		try {
			BufferedReader responses = 
					new BufferedReader
					(new InputStreamReader(socket.getInputStream()));
			PrintWriter writer = new PrintWriter(socket.getOutputStream());
			System.out.print("Hit");
			StringBuilder sb = new StringBuilder();
			while (!responses.ready()){}
			boolean trip = false;
			while (responses.ready()) {
				if (trip){
					sb.append("\n");
				}
				trip = true;
				sb.append(responses.readLine());
			}
			String response = handleCall(sb.toString());
			if (response != null){
				System.out.println("Sending response:"+response);
				writer.print(response);
			}
			writer.flush();
			socket.close();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		} 
	}
	private String handleCall(String message){
		String type = message.substring(0, message.indexOf(":"));
		if (type.equals("pk_host_request")){
			if (host){
				System.out.println("True:"+tableName);
				return "True:"+tableName+"\n";
			}
			else{
				return "False\n";
			}
		}
		else if (type.equals("pk_join_game")){
			String ip = socket.getInetAddress().toString().substring(1);
			String playerName = message.substring(message.indexOf(":") + 1);
			String returnVal = ""+manager.addPlayer(ip,playerName);
			delegate.playerJoined();
			return "playerNum:"+returnVal+"\n";
		}
		else if (type.equals("pk_game_start")){
			System.out.print("Got Queue");
			String iplist = message.substring(message.indexOf(":") + 1);
			String[] ips = iplist.split(",");
			for (String ip: ips){
				manager.addIp(ip);
			}
			GamePlayPanel game = new GamePlayPanel(manager);
		}
		else if (type.equals("pk_game_state")){
			System.out.print("Got Data");
			String gameState = message.substring(message.indexOf(":") + 1);
			manager.updateGameState(gameState);
		}
		return null;
	}
}